/**
 * 
 */
package arisufascion.com.activity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import arisufascion.com.AbstractActivity;
import arisufascion.com.MainApplication;
import arisufascion.com.R;
import arisufascion.com.compone.LoadMoreListView.OnLoadMoreListener;
import arisufascion.com.constant.Constants;
import arisufascion.com.constant.Utils;
import arisufascion.com.constant.WriteLog;
import arisufascion.com.db.MySharePreferences;
import arisufascion.com.db.ProductDataSource;
import arisufascion.com.model.Product;
import arisufascion.com.tabs.BadgeTabManager;
import arisufascion.com.tabs.TabGroupActivity;

import com.androidquery.AQuery;

/**
 * @author Kelvin
 * 
 */
public class ActivityCart extends AbstractActivity {
	private MainApplication apps;
	private int page = 1;
	private LayoutInflater inflater;
	private boolean isLoading = true;
	private ProgressDialog dialog;
	private List<Product> products = new ArrayList<Product>();
	private int categories_id;
	private ProductDataSource dbAdapter;
	private TableRow row;
	private TableLayout tbl_product;
	private AQuery aq;
	private double total_result_price = 0;
	private double total_price = 0;
	private TextView txt_total_result_price, txt_total;
	private CheckBox checkBoxTermns;
	protected static final int REFRESH = 0;
	private EditText edittext_customer_comment;

	private Handler _hRedraw;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shopping);
		apps = (MainApplication) getApplication();
		aq = new AQuery(self);
		
		findViewById(R.id.btn_privacy).setOnClickListener(onClick);
		findViewById(R.id.btn_menu).setOnClickListener(onClick);
		findViewById(R.id.btn_wholesale).setOnClickListener(onClick);
		findViewById(R.id.btn_shipping).setOnClickListener(onClick);
		
		_hRedraw = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case REFRESH:
					redrawEverything();
					break;
				}
			}
		};

		

//		findViewById(R.id.btn_menu).setOnClickListener(onClick);
		findViewById(R.id.btnCheckOut).setOnClickListener(eventOnClick);
		findViewById(R.id.btn_continue).setOnClickListener(eventOnClick);
		findViewById(R.id.btn_clear_all).setOnClickListener(eventOnClick);
		
		edittext_customer_comment=(EditText)findViewById(R.id.edittext_customer_comment);
		tbl_product = (TableLayout) findViewById(R.id.tbl_product);
		txt_total_result_price = (TextView) findViewById(R.id.txt_total_result_price);
		txt_total = (TextView) findViewById(R.id.txt_total);
		checkBoxTermns=(CheckBox)findViewById(R.id.checkBoxTermns);

	}

	OnLoadMoreListener loadMoreListener = new OnLoadMoreListener() {

		@Override
		public void onLoadMore() {
			new getProductsFromServer().execute();
		}
	};

	public class getProductsFromServer extends
			AsyncTask<Void, Void, List<Product>> {

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Show Dialog
			if (isLoading) {
				dialog = new ProgressDialog(getParent());
				dialog.setMessage("Fetching data...");
				dialog.show();
				isLoading = false;
			}
		}

		@Override
		protected List<Product> doInBackground(Void... params) {
			_hRedraw.sendEmptyMessage(REFRESH);
			
			return dbAdapter.getProducts();

		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(List<Product> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			// Dismiss Dialog
			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
			}

			if (result != null) {
				total_result_price = 0;
				for (Product product : result) {
					tbl_product.addView(setUp(product),
							new TableLayout.LayoutParams(
									LayoutParams.WRAP_CONTENT,
									LayoutParams.WRAP_CONTENT));

					total_result_price += product.getQuantity()
							* product.getProduct_price();
				}
				DecimalFormat df = new DecimalFormat("#.##");
				txt_total_result_price.setText("$" +String.format("%.2f", total_result_price));

				txt_total.setText("$" +String.format("%.2f", total_result_price));
				
				int index=0 ;
				for (int i = 0; i < dbAdapter.getProducts().size(); i++) {
					index+=dbAdapter.getProducts().get(i).getQuantity();
				}

				BadgeTabManager.getInstance().setBadgeAtIndex(index, 1);
			}
		}

		public TableRow setUp(Product product) {
			row = new TableRow(self);
			View v;
			LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.row_cart, null);
			ImageView iv_cart = (ImageView) v.findViewById(R.id.iv_cart);

			TextView product_name = (TextView) v
					.findViewById(R.id.txt_cart_product_name);

			final TextView product_price = (TextView) v
					.findViewById(R.id.txt_cart_price_product);
			
			final TextView txt_color_name = (TextView) v
					.findViewById(R.id.txt_color_name);
			

			final EditText product_quantity = (EditText) v
					.findViewById(R.id.edittext_cart_quantity);

			ImageButton btn_update = (ImageButton) v
					.findViewById(R.id.btn_update);

			ImageButton btn_delete = (ImageButton) v
					.findViewById(R.id.btn_delete);
			ProgressBar progressBar = (ProgressBar) v
					.findViewById(R.id.progressBar);

			// set data for row
			product_name.setText(product.getProduct_name());
			product_price.setText("$"
					+ String.valueOf(product.getProduct_price()
							* product.getQuantity()));
			product_quantity.setText(String.valueOf(product.getQuantity()));
			
			if(product.getColor_id()>0){
				txt_color_name.setVisibility(VISIBLE);
				txt_color_name.setText("Color "+product.getColor_id());
			}else{
				txt_color_name.setVisibility(GONE);
			}

			try {
				String url = String.format(Constants.SERVER_URL_IMAGES,
						String.valueOf(dbAdapter
								.getAllImageSliders(
										Integer.parseInt(product
												.getVirtuemart_product_id()))
								.get(0).getFile_url()));

				WriteLog.d("Kelvin:", url);

				aq.id(iv_cart).progress(progressBar)
						.image(url, true, true, 0, R.drawable.icon_logo);

			} catch (Exception e) {
				// TODO: handle exception
			}

			btn_update.setTag(btn_update.getId(), product);
			btn_delete.setTag(btn_delete.getId(), product);

			row.addView(v);

			btn_update.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
				//step 1	
				if(product_quantity.getText().toString().length()>0){
					Product pr = (Product) v.getTag(v.getId());
					//step 2
					if (Integer.parseInt(product_quantity.getText().toString()) > 0) {
						
						//step 3
						if(pr.getColor_quantity()>0){
							
							if (pr.getColor_quantity() >= Integer
									.parseInt(product_quantity.getText().toString())) {

								pr.setQuantity(Integer.parseInt(product_quantity
										.getText().toString()));

								dbAdapter.updateProduct(pr);


								product_price.setText("$"
										+ String.valueOf(pr.getProduct_price()
												* pr.getQuantity()));

								_hRedraw.sendEmptyMessage(REFRESH);
								new getProductsFromServer().execute();

							} else {
								product_quantity.setError(Html
										.fromHtml("<font color='red'>Max quantity reached, new quantity set to "
												+ pr.getColor_quantity() + "</font>"));
							}
						}else{
							if (pr.getQuantity() >= Integer
									.parseInt(product_quantity.getText().toString())) {

								pr.setQuantity(Integer.parseInt(product_quantity
										.getText().toString()));

								dbAdapter.updateProduct(pr);


								product_price.setText("$"
										+ String.valueOf(pr.getProduct_price()
												* pr.getQuantity()));

								_hRedraw.sendEmptyMessage(REFRESH);
								new getProductsFromServer().execute();

							} else {
								product_quantity.setError(Html
										.fromHtml("<font color='red'>Max quantity reached, new quantity set to "
												+ pr.getQuantity() + "</font>"));
							}
						}
					
					} else {
						product_quantity.setError(Html
								.fromHtml("<font color='red'>Minim quantity is 1"
										+ "</font>"));
					}
				}else{
					product_quantity.setError(Html
							.fromHtml("<font color='red'>Please enter quantity"
								+ "</font>"));
				}

				}
			});

			btn_delete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					Product pr = (Product) v.getTag(v.getId());

					dbAdapter.deleteProduct(Integer.parseInt(pr
							.getVirtuemart_product_id()),pr.getColor_id());

					_hRedraw.sendEmptyMessage(REFRESH);
					
					new getProductsFromServer().execute();

				}
			});

			return row;

		}


	}

	public OnClickListener eventOnClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			
			case R.id.btnCheckOut:
				
				if(checkBoxTermns.isChecked()){
					MySharePreferences.saveCustomerComment(edittext_customer_comment.getText().toString(), self);
					
				if (!MySharePreferences.getLogin(getParent())) {

					Intent intent_checkout = new Intent(self,
							ActivityCheckout.class);
					
//					startActivity(intent_checkout);
					
					TabGroupActivity tabGroupActivity = (TabGroupActivity) getParent();
					tabGroupActivity.startChildActivity("ActivityCheckout",
							intent_checkout);
				} else{

					Intent intent_comfirm_checkout = new Intent(self,
							ActivityComfirmCheckOut.class);
//					startActivity(intent_comfirm_checkout);
					
					TabGroupActivity tabGroupActivity = (TabGroupActivity) getParent();
					tabGroupActivity.startChildActivity(
							"ActivityComfirmCheckOut", intent_comfirm_checkout);

				}
				}else{
					Spanned error_msg = Html
							.fromHtml("<font color='red'>Please check to read termns of services" + "</font>");
					checkBoxTermns.setError(error_msg);
				}
				break;
			case R.id.btn_continue:
				finish();

				break;

			case R.id.btn_clear_all:
				dbAdapter.deleteAllProduct();
				tbl_product.removeAllViews();
				new getProductsFromServer().execute();
				break;

			default:
				break;
			}

		}
	};

	private void redrawEverything() {
		tbl_product.removeAllViews();
		tbl_product.removeAllViewsInLayout();
		tbl_product.invalidate();
		tbl_product.refreshDrawableState();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		WriteLog.d(TAG, "Pause Activity");
		if(dbAdapter.isOpen()){
			dbAdapter.close();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		WriteLog.d(TAG, "Resume Activity");
		if(dbAdapter!=null){
			dbAdapter.open();
		}else{
			dbAdapter=new ProductDataSource(self);
			dbAdapter.open();
		}
	//	if(!dbAdapter.isOpen()){
			new getProductsFromServer().execute();
	//	}
		//new getProductsFromServer().execute();
	}
}